package com.acooly.module.openapi.client.provider.wsbank.marshall;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.provider.wsbank.WsbankConstants;
import com.acooly.module.openapi.client.provider.wsbank.utils.SignUtils;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.signature.SignTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author weichk
 */
@Slf4j
@Service
public class WsbankSignMarshall extends WsbankMarshallSupport {

    /**
     * 验签
     * @param request
     * @return
     */
    public boolean verySign(HttpServletRequest request, String partnerId) {
        boolean isPass = true;
        try {
            Map<String, String> waitSignMap = getDateMap(request);
            String signature = waitSignMap.get(WsbankConstants.SIGN);
            String plain = SignUtils.getSignContent(waitSignMap);
            doVerifySign(plain);
        } catch (Exception e) {
            isPass = false;
            log.info("验签失败[" + e.getMessage() + "]");
        }
        return isPass;
    }

    /**
     * 图片上传签名
     * @param waitForSign
     * @return
     */
    public String uploadDoSign(String waitForSign) {
        return Safes.getSigner(SignTypeEnum.Rsa).sign(waitForSign, getKeyPair());
    }

    /**
     * 将收到的报文转化为map
     *
     * @param request
     * @return
     */
    public Map<String, String> getDateMap(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("utf-8");
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
                String name = entry.getKey();
                String[] values = entry.getValue();
                String valueStr = "";
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        valueStr = (i == values.length - 1) ? valueStr + values[i]
                                : valueStr + values[i] + ",";
                    }

                    params.put(name, valueStr);
                }

            }
            return params;
        } catch (Exception e) {
            throw new ApiClientException("签名失败", e);
        }
    }
}
